﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Chapter_9__Recursion_
{
    public static class MergeSort
    {
        public static void Sort<T>(T[] array) where T : IComparable
        {
            mergesort(array, 0, array.Length - 1);
            //mergesort(array);
        }

        // This was created just to make it a little easier to follow in debug.
        static void mergesort<T>(T[] array)
        {
            if (array.Length > 1)
            {
                int middle = array.Length / 2;
                T[] leftArray = new T[middle];
                T[] rightArray = new T[array.Length - middle];

                int current = 0;
                for (int i = 0; i < leftArray.Length; i++)
                    leftArray[i] = array[current++];
                for (int i = 0; i < rightArray.Length; i++)
                    rightArray[i] = array[current++];

                mergesort(leftArray);
                mergesort(rightArray);
            }
        }

        static void mergesort<T>(T[] array, int low, int high) where T : IComparable
        {
            if (low < high)
            {
                int middle = (low + high) / 2;
                //mergesort(array, low, middle);      // Sort left half
                //mergesort(array, middle + 1, high); // Sort right half
                merge(array, low, middle, high);    // Merge them
            }
        }

        static void merge<T>(T[] array, int low, int middle, int high) where T : IComparable
        {
            T[] helper = new T[array.Length];

            // Copy both halves into a helper array.
            for (int i = low; i <= high; i++)
            {
                helper[i] = array[i];
            }

            int helperLeft = low;
            int helperRight = middle + 1;
            int current = low;

            while (helperLeft <= middle && helperRight <= high)
            {
                int compareResult = helper[helperLeft].CompareTo(helper[helperRight]);
                if (compareResult <= 0)
                {
                    array[current] = helper[helperLeft];
                    helperLeft++;
                }
                else
                {
                    array[current] = helper[helperRight];
                    helperRight++;
                }
                current++;
            }

            int remaining = middle - helperLeft;
            for (int i = 0; i <= remaining; i++)
            {
                array[current + i] = helper[helperLeft + i];
            }
        }
    }
}
